package com.btpn.infra.web.struts2.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.btpn.infra.utils.ErrorMessageUtil;
import com.opensymphony.xwork2.ActionSupport;

@ParentPackage(value = "custody")
public class ExceptionAction extends ActionSupport implements ServletRequestAware {

	private static final long serialVersionUID = 192341885687421595L;
		
	private HttpServletRequest servletRequest;
	
	private InputStream inputStream;
	private StringWriter sw;
	private String exceptionBuss;
	private String exceptionMsg;
	private String exceptionStack;
	
	@Action(value = "/show-exception", results = { 
			@Result(name="success", location="t_error")
	})
	public String showException() {
		
		Exception exception = (Exception) getServletRequest().getAttribute("exception");
		if (exception != null) {
			exceptionBuss = ErrorMessageUtil.getErrorHTML(exception.getMessage());
			exceptionMsg = exception.fillInStackTrace().toString();
			
			sw = new StringWriter();
			exception.printStackTrace(new PrintWriter(sw));
			exceptionStack = sw.toString();
			System.out.println(exceptionStack);
		}
        
		return SUCCESS;
	}
	
	@Action(value = "/logException", results = { 
			@Result(name = "success", type = "stream", params = {"contentType", "application/octet-stream", "inputName", "inputStream", 
					"contentDisposition", "attachment;filename=CMT.txt", "bufferSize", "1024"})
	})
	public String logException() {
		
		//stream
		StringWriter sb = new StringWriter();
		sb.append(exceptionStack);
		sb.flush();
	    
	    inputStream = new ByteArrayInputStream(sb.toString().getBytes());
	    
		return SUCCESS;
	}

	public HttpServletRequest getServletRequest() {
		return servletRequest;
	}
	
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.servletRequest = request;
	}
	
	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getExceptionMsg() {
		return exceptionMsg;
	}

	public void setExceptionMsg(String exceptionMsg) {
		this.exceptionMsg = exceptionMsg;
	}

	public String getExceptionStack() {
		return exceptionStack;
	}

	public void setExceptionStack(String exceptionStack) {
		this.exceptionStack = exceptionStack;
	}

	public String getExceptionBuss() {
		return exceptionBuss;
	}

	public void setExceptionBuss(String exceptionBuss) {
		this.exceptionBuss = exceptionBuss;
	}
}
